<?php

/**
 * 系统基础
 */

namespace app\member\api;

use \app\base\api\BaseApi;

class MemberApi extends BaseApi {

    protected $userId = 0;

    public function __construct() {
        parent::__construct();
        $this->checkLogin();
    }

    /**
     * 检测登录
     */
    private function checkLogin() {
        if (!target('Member/Member', 'service')->checkUser($_SERVER['HTTP_AUTHUID'], $_SERVER['HTTP_AUTHTOKEN'])) {
            $this->error(target('Member/Member', 'service')->getError(), 401);
        }
        $this->userId = $_SERVER['HTTP_AUTHUID'];
    }

    /**
     * 获取用户资料
     */
    public function info() {
        $info = target('Member/Member', 'service')->getUser($this->userId);
        if (empty($info)) {
            $this->error(target('Member/Member', 'service')->getError());
        }
        $this->success('ok', $info);
    }

    /**
     * 更新用户资料
     */
    public function update() {
        $data = target('Member/Member', 'service')->updateUser($this->userId, $this->data);
        if (!$data) {
            $this->error(target('Member/Member', 'service')->getError());
        }
        $this->success('资料保存成功!');
    }

    /**
     * 更新头像
     */
    public function avatar() {
        $file = target('member/Member', 'service')->upload($this->userId, 'jpg,jpeg,gif,png,bmp', 256, 256);
        if (!$file || empty($file['file'])) {
            $this->error(target('member/Member', 'service')->getError());
        }
        if (!target('member/Member', 'service')->avatarUser($this->userId,  $file['file']['url'])) {
            $this->error(target('member/Member', 'service')->getError());
        }
        $this->success('头像修改成功!', $file);
    }

    /**
     * 上传照片
     */
    public function upload() {
        $service = target('Member/Member', 'service');
        $updateData = $service->upload($this->userId, 'jpg,png,bmp,jpeg', 800, 800);
        if (!$updateData) {
            $this->error($service->getError());
        }
        $this->success('上传成功!', $updateData);
    }

    /**
     * 修改密码
     */
    public function password() {
        $userInfo = target('member/MemberUser')->getInfo($this->userId);
        if (md5($this->data['old_password']) <> $userInfo['password']) {
            $this->error('原始密码输入不正确!');
        }
        if (empty($this->data['password'])) {
            $this->error('请输入新密码!');
        }
        if ($this->data['password'] <> $this->data['password2']) {
            $this->error('两次密码输入不正确!');
        }
        $data = [];
        $data['user_id'] = $this->userId;
        $data['password'] = md5($this->data['password']);
        if (!target('member/MemberUser')->edit($data)) {
            $this->error('密码修改失败!');
        }
        $this->success('密码修改成功!');
    }


}